
package cn.stylefeng.guns.sys.modular.system.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.stylefeng.guns.base.auth.annotion.Permission;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.log.BussinessLog;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.sys.core.constant.Const;
import cn.stylefeng.guns.sys.modular.system.entity.Kms;
import cn.stylefeng.guns.sys.modular.system.entity.OperationLog;
import cn.stylefeng.guns.sys.modular.system.mapper.OperationLogMapper;
import cn.stylefeng.guns.sys.modular.system.service.KmsService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author YuJiBiao
 * @version: 1.0
 * @Date 2020/7/8 16:30
 **/
@Controller
@RequestMapping("/kmsPage")
public class KMSPageController extends BaseController {

    @Autowired
    KmsService kmsService;

    private String PREFIX = "/modular/system/kms/";
    @Autowired
    OperationLogMapper operationLogMapper;


    @RequestMapping("/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) Integer index,
                       @RequestParam(required = false) String backId) {
        //获取分页参数
        Page page = LayuiPageFactory.defaultPage();
        Page<Map<String, Object>> mapPage = kmsService.selectKmsList( index,backId);
        return LayuiPageFactory.createPageInfo(mapPage);
    }


    /**
     * 清空日志
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:34 PM
     */
    @BussinessLog(value = "归档密钥")
    @RequestMapping("/downKey")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Object downLog(@RequestParam(required = false) String beginTime,@RequestParam(required = false) String endTime) {
        List<Kms> downList = kmsService.downList(beginTime, endTime);
        File file = FileUtil.appendLines(downList, "D:\\kms\\秘钥归档"+ beginTime + "-"+endTime+".log","UTF-8");
        return file.getAbsolutePath();
    }
    /**
     * layui上传组件 通用文件上传接口
     *
     * @author fengshuonan
     * @Date 2019-2-23 10:48:29
     */
    @RequestMapping(method = RequestMethod.POST, path = "/kms/upload")
    @ResponseBody
    public ResponseData layuiUpload(@RequestPart("file") MultipartFile file) throws IOException {
        //生成秘钥
        LoginUser user = LoginContextHolder.getContext().getUser();
        StringWriter writer = new StringWriter();
        IOUtils.copy(file.getInputStream(), writer, StandardCharsets.UTF_8.name());
        String str = writer.toString();
        List<Kms> kmsList = JSON.parseArray(str, Kms.class);
        Integer num = 0;
        String message = "";
        for (Kms kms:kmsList) {
            Kms byId = kmsService.getById(kms.getKmsId());
            if(byId == null) {
                kmsService.save(kms);
                num++;
            }
        }
        try {
            if(num != 0 ) {
                OperationLog operationLog = new OperationLog();
                operationLog.setLogType("操作日志");
                operationLog.setLogName("恢复密钥");
                operationLog.setUserId(user.getId());
                operationLog.setClassName(this.getClass().getName());
                operationLog.setMethod("bakKey");
                operationLog.setCreateTime(new Date());
                operationLog.setSucceed("成功");
                operationLog.setMessage("恢复密钥 一共"+num+"条记录");
                operationLogMapper.insert(operationLog);
                message = "恢复成功！共恢复"+num+"条记录";
                return ResponseData.success(0, message, null);
            }

        } catch (Exception e) {
        }
        message = "没有可以用于恢复的数据";
        return ResponseData.success(0, message, null);
    }
    /**
     * 备份
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:34 PM
     */
    @BussinessLog(value = "归档密钥")
    @RequestMapping(value = "/bakKms",method = RequestMethod.POST)
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Object bakKms() throws IOException {
        LoginUser user = LoginContextHolder.getContext().getUser();

        List<Kms> downList = kmsService.bakKms();
        String jsonStr = JSON.toJSONString(downList);
        String filePath="D:\\kms\\备份密钥"+ DateUtil.formatDate(new Date()) +".json";
        File file = new File(filePath);
        file.createNewFile();
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(jsonStr.getBytes());
        fos.close();
        try {
            OperationLog operationLog = new OperationLog();
            operationLog.setLogType("操作日志");
            operationLog.setLogName("备份密钥");
            operationLog.setUserId(user.getId());
            operationLog.setClassName(this.getClass().getName());
            operationLog.setMethod("bakKey");
            operationLog.setCreateTime(new Date());
            operationLog.setSucceed("成功");
            operationLog.setMessage("备份密钥成功路径---》"+filePath);
            operationLogMapper.insert(operationLog);
        } catch (Exception e) {
        }
        return filePath;
    }

    /**
     *
     *
     * @author fengshuonan
     * @Date 2018/12/23 4:56 PM
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "kms.html";
    }

    /**
     *
     *
     * @author fengshuonan
     * @Date 2018/12/23 6:30 PM
     */
    @RequestMapping(value = "/kms_add")
    public String roleAdd() {
        return PREFIX + "/kms_add.html";
    }


    /**
     * 密钥分配
     * @param index
     * @param backId
     * @return
     */
    @RequestMapping("/distributionList")
    @ResponseBody
    public Object distributionList(@RequestParam(required = false) Integer index,
                       @RequestParam(required = false) String backId) {
        //获取分页参数
        Page page = LayuiPageFactory.defaultPage();
        Page<Map<String, Object>> mapPage = kmsService.selectkmsDistributionList( index,backId);
        return LayuiPageFactory.createPageInfo(mapPage);
    }


    /**
     *
     *
     * @author fengshuonan
     * @Date 2018/12/23 4:56 PM
     */
    @RequestMapping("/kmsDistribution")
    public String kmsDistribution() {
        return "/modular/system/kmsDistribution/kmsDistribution.html";
    }

    /**
     *
     *
     * @author fengshuonan
     * @Date 2018/12/23 4:56 PM
     */
    @RequestMapping("/connectionKey")
    public String connectionKey() {
        return "/modular/system/connectionKey/kmsDistribution.html";
    }

    /**
     * 密钥分配
     * @param index
     * @param backId
     * @return
     */
    @RequestMapping("/connectionKeyList")
    @ResponseBody
    public Object connectionKeyList(@RequestParam(required = false) Integer index,
                                   @RequestParam(required = false) String backId) {
        //获取分页参数
        Page page = LayuiPageFactory.defaultPage();
        LoginUser user = LoginContextHolder.getContext().getUser();
        Page<Map<String, Object>> mapPage = kmsService.connectionKeyList( index,backId,user);
        return LayuiPageFactory.createPageInfo(mapPage);
    }

    /**
     *
     * @param id
     * @return
     */
    @RequestMapping("/getKey")
    @ResponseBody
    public Object getKey(@RequestParam(required = true) Long id) {
        Kms kms = kmsService.getById(id);
        return ResponseData.success(kms);
    }

    /**
     * 清空日志
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:34 PM
     */
    @BussinessLog(value = "归档密钥")
    @RequestMapping("/getChartsData")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Object getChartsData() {
        return kmsService.getChartsData();
    }

}
